﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RedSand.Site.Models;
using RedSand.Site.Controllers;
using RedSand.Web.Mvc;

namespace Site.Controllers
{
    public class CategoryController : BaseController
    {
        public ActionResult Manager()
        {
            return View(new ManagerModel { Title = "Category manager" });
        }

        [AjaxOrChildAction]
        public ActionResult List(int level = 1, int parent = 0)
        {
            if (level == 3)
            {
                ViewBag.ParentID = RsDataManager.GetInfo<CategoryInfo>("CategoryGetInfo", "CategoryID", parent).ParentID;
            }
            switch (level)
            {
                case 1: return PartialView("ListParent", RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = parent }));
                case 2: return PartialView("ListChild", RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = parent }));
                case 3: return PartialView("ListChild2", RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = parent }));
                default: return new EmptyResult();
            }
        }
        [AjaxOrChildAction]
        public ActionResult liCategory(int categoryId=0)
        {
            var info = RsDataManager.GetInfo<CategoryInfo>("CategoryGetInfo", "CategoryID", categoryId);
            ViewBag.CateParent = info.Name;
            ViewBag.Alias = info.Alias;
            return PartialView("liCategory", RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = categoryId }));
        }


        [AjaxOrChildAction]
        public ActionResult ListMenu(int parent = 0)
        {
            if (parent == 0)
            {
                ViewBag.Title = "Quick CAtegory";
                return PartialView("ListMenu", RsDataManager.GetList<CategoryInfo>("GetQuickMenu"));
            }
            else
            {
                ViewBag.Title = GetName(parent);
                return PartialView("ListMenu", RsDataManager.GetList<CategoryInfo>("CategoryGetLevel", new { CategoryID = parent }));
            }
        }

        [AjaxOrChildAction]
        public ActionResult isPopular()
        {

            return PartialView("isPopular", RsDataManager.GetList<CategoryInfo>("CategoryGetListByPopular"));
            
        }


        [HttpGet]
        public ActionResult QuickMenu(int parent = 0)
        {
            return PartialView("QuickMenu", RsDataManager.GetList<CategoryInfo>("GetQuickMenu", new { ParentID = parent }));
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult Create(int count, int parent = 0, int level = 1)
        {
            switch (level)
            {
                case 1: return PartialView("CreateParent", new CategoryInfo { Order = count + 1, ParentID = parent });
                case 2: return PartialView("CreateChild", new CategoryInfo { Order = count + 1, ParentID = parent });
                case 3: return PartialView("CreateChild2", new CategoryInfo { Order = count + 1, ParentID = parent });
                default: return new EmptyResult();
            }
        }
        [AjaxOrChildAction, HttpPost]
        public ActionResult Create(CategoryInfo info, int level, int count, string NewImage)
        {
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrWhiteSpace(NewImage)) info.Image = SaveImage(null);
                int result = RsDataManager.Save("CategorySave", info);
                if (result > 0)
                {
                    if (level == 3 && !info.IsCustomPc.Value)
                    {
                        AddMessage("Add propertise for product of this category");
                        return RedirectToAction("Edit", new { id = result, count = count, level = level, create = true });
                    }
                    else
                    {
                        AddMessage(Message.CreateSuccess);
                        return RedirectToAction("List", new { parent = info.ParentID, level = level });
                    }
                }
                else
                {
                    DeleteFile(info.Image);
                    return AjaxMessage(Message.CreateError);
                }
            }
            return AjaxModelError();
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult Edit(int id, int count, int level = 1, bool create = false)
        {
            ViewBag.Create = create;
            ViewBag.Count = count;
            var info = RsDataManager.GetInfo<CategoryInfo>("CategoryGetInfo", "CategoryID", id);
            switch (level)
            {
                case 1: return PartialView("EditParent", info);
                case 2: return PartialView("EditChild", info);
                case 3: return PartialView(info.IsCustomPc.Value ? "EditChild22" : "EditChild2", info);
                default: return new EmptyResult();
            }
        }
        [AjaxOrChildAction, HttpPost]
        public ActionResult Edit(CategoryInfo info, int level, string NewImage)
        {
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrWhiteSpace(NewImage)) info.Image = SaveImage(info.Image);
                if (RsDataManager.Save("CategorySave", info)>0)
                {
                    AddMessage(Message.UpdateSuccess);
                    return RedirectToAction("List", new { parent = info.ParentID, level = level });
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(NewImage)) DeleteFile(info.Image);
                    return AjaxMessage(Message.UpdateError);
                }
            }
            return AjaxModelError();
        }

        [AjaxOrChildAction]
        public ActionResult Delete(int id, int parent = 0, int level = 1)
        {
            var childs = RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = id });
            if (childs != null)
            {
                return AjaxMessage("Cannot delete item which has child item");
            }
            else
            {
                var info = RsDataManager.GetInfo<CategoryInfo>("CategoryGetInfo", "CategoryID", id);
                if (RsDataManager.Delete("CategoryDelete", "CategoryID", id))
                {
                    DeleteFile(info.Image);
                    AddMessage(Message.DeleteSuccess);
                    return RedirectToAction("List", new { level = level, parent = parent });
                }
                return AjaxMessage(Message.DeleteError);
            }
        }

        [AjaxOrChildAction]
        public ActionResult Properties(int category)
        {
            ViewBag.Category = category;
            return PartialView(RsDataManager.GetList<PropertyInfo>("PropertyGetList", new { CategoryID = category }));
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult CreateProperty(int count, int category)
        {
            return PartialView(new PropertyInfo { Order = count + 1, CategoryID = category });
        }

        [AjaxOrChildAction, HttpPost]
        public ActionResult CreateProperty(PropertyInfo info)
        {
            if (ModelState.IsValid)
            {
                if (RsDataManager.Save("PropertySave", info) > 0)
                {
                    AddMessage(Message.CreateSuccess);
                    return RedirectToAction("Properties", new { category = info.CategoryID });
                }
                else
                {
                    return AjaxMessage(Message.CreateError);
                }
            }
            return AjaxModelError();
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult EditProperty(int id, int count)
        {
            ViewBag.Count = count;
            return PartialView(RsDataManager.GetInfo<PropertyInfo>("PropertyGetInfo", "PropertyID", id));
        }

        [AjaxOrChildAction, HttpPost]
        public ActionResult EditProperty(PropertyInfo info)
        {
            if (ModelState.IsValid)
            {
                if (RsDataManager.Save("PropertySave", info)>0)
                {
                    AddMessage(Message.UpdateSuccess);
                    return RedirectToAction("Properties", new { category = info.CategoryID });
                }
            }
            return AjaxModelError();
        }

        [AjaxOrChildAction]
        public ActionResult DeleteProperty(int id, int category)
        {
            if (ModelState.IsValid)
            {
                if (RsDataManager.Delete("PropertyDelete", "PropertyID",id))
                {
                    AddMessage(Message.DeleteSuccess);
                    return RedirectToAction("Properties", new { category = category });
                }
            }
            return AjaxModelError();
        }


        [AjaxOrChildAction]
        public MvcHtmlString SelectList(int? parent, string name, string id, bool? isCustonPc,  bool? validate, int? selectedValue)
        {
            List<CategoryInfo> list = null;
            if (parent.HasValue)
            {
                list = RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = parent, IsCustomPc = isCustonPc });
            }
            return SelectList(list, name, id,  validate, selectedValue);
        }

        [AjaxOrChildAction]
        public MvcHtmlString SelectListByLevel(int level, string name, string id, bool? validate, int? selectedValue)
        {
            var list = RsDataManager.GetList<CategoryInfo>("CategoryGetListByLevel", new { Level = level });
            return SelectList(list, name, id, validate, selectedValue);
        }

        public MvcHtmlString SelectListForCustomPc(string name, string id, bool? validate, int? selectedValue)
        {
            var list = RsDataManager.GetList<CategoryInfo>("CategoryGetListForCustomPc");
            return SelectList(list, name, id, validate, selectedValue);
        }

        public MvcHtmlString SelectListIsCustomPc(string name, string id, bool? validate, int? selectedValue)
        {
            var list = RsDataManager.GetList<CategoryInfo>("CategoryGetListIsCustomPc");
            return SelectList(list, name, id, validate, selectedValue);
        }

        private MvcHtmlString SelectList(List<CategoryInfo> list, string name, string id, bool? validate, int? selectedValue)
        {
            list = list ?? new List<CategoryInfo>();
            TagBuilder select = new TagBuilder("select");
            select.Attributes["name"] = name ?? "CategoryID";
            select.GenerateId(id ?? "CategoryID");
            if (validate.HasValue && validate.Value)
            {
                select.Attributes["data-val"] = "true";
                select.Attributes["data-val-required"] = "The field is required.";
            }
            TagBuilder option = new TagBuilder("option");
            option.Attributes["value"] = "";
            select.InnerHtml += option.ToString();
            foreach (var item in list)
            {
                option = new TagBuilder("option");
                option.Attributes["value"] = item.CategoryID.ToString();
                option.InnerHtml = item.Name;
                if (item.CategoryID == (selectedValue ?? 0))
                {
                    option.Attributes["selected"] = "selected";
                }
                select.InnerHtml += option.ToString();
            }
            return MvcHtmlString.Create(select.ToString());
        }

        [AjaxOrChildAction]
        public MvcHtmlString GetName(int id)
        {
            var info = RsDataManager.GetInfo<CategoryInfo>("CategoryGetInfo", "CategoryID", id);
            if (info == null) return MvcHtmlString.Empty;
            return MvcHtmlString.Create(info.Name);
        }

    }
}
